$(function() {

	var doc = $(document),
		body = $('body'),
		topMenu = body.find(".top-menu");
		
	doc.on('fileopened', function (e, file) {
		loadFileAsText(file);
	});
		
	var saveFile = function (content, fileName) {
		var textFileAsBlob = new Blob([content], {type:'text/plain'});
		var fileNameToSaveAs = fileName;

		var downloadLink = document.createElement("a");
		downloadLink.download = fileNameToSaveAs;
		downloadLink.innerHTML = "Download File";
		// Firefox requires the link to be added to the DOM
		// before it can be clicked.
		downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
		$(downloadLink).on('click', function () {
			$(downloadLink).remove();
		});
		downloadLink.style.display = "none";
		document.body.appendChild(downloadLink);

		downloadLink.click();
	};
	
	var loadFileAsText = function (file) {
		var fileToLoad = file,
			fileReader = new FileReader(),
			format;
			
		filename = file.name;
		if (/\.qsd/.test(filename)) {
			format = 'qsd';
		} else {
			return;
		}
		fileReader.onload = function(fileLoadedEvent) {
			var textFromFileLoaded = fileLoadedEvent.target.result;
			
			parseQsd(textFromFileLoaded);
		};
		
		fileReader.readAsText(fileToLoad, "UTF-8");
	};
	
	var parseQsd = function (text) {
		var lines = text.split("\r\n");
		if (lines.length === 1) {
			lines = text.split("\n");
		}
		
		var currentline = 0,
			currentType = "",
			data = "",
			addSeed = function (type, data) {
				if (type !== "") {
					var seed = makeSeed(type, data);
					//console.log(seed);
					doc.trigger('seedadded', seed);
				}
			};
			
		seeds = {};
		
		while(currentline < lines.length) {
			var line = lines[currentline];
			
			if (/\mcbank:/i.test(line)) {
				addSeed(currentType, data);
				data = "";
				currentType = 'mcbank';
			} else if (/calc:/i.test(line)) {
				addSeed(currentType, data);
				data = "";
				currentType = 'calculated';
			} else if (/mc:/i.test(line)) {
				addSeed(currentType, data);
				data = "";
				currentType = 'mc';
			} else if (/matchbank:/i.test(line)) {
				addSeed(currentType, data);
				data = "";
				currentType = 'matchbank';
			} else if (/tf:/i.test(line)) {
				addSeed(currentType, data);
				data = "";
				currentType = 'tf';
			} 
			
			if (line !== "") {
				data += lines[currentline] + '\r\n';
			}
			
			currentline++;
		}
		addSeed(currentType, data);
	};
	
	var makeSeed = function (type, data) {
		// fill in the rest of the question types
		var seed;
		//console.log(type);
		if (type === 'mcbank') {
			seed = MCBank(data);
		} else if (type === 'mc') {
			seed = MultiChoice(data);
		} else if (type === 'matchbank') {
			seed = Matching(data);
		} else if (type === 'tf') {
			seed = trueFalse(data);
		} else if (type === 'calculated') {
			seed = Calculated(data);
		}
		
		return seed;
	};
	
	$.widget("MQM.menuButtons", {

		_create: function () {
			var self = this;
			
			self.initializeButtons();
		},
	
		initializeButtons: function () {
			var self = this,
				open = function () {
					fileInput.click();
				},
				save = function () {
					var position = {
						left: body.find('.save-button')[0].offsetLeft,
						top: body.find('.top-menu').height() + 2
					};
					
					var saveHtml = $('<div></div>');
					dialogue(saveHtml, position);
					
					saveHtml.savedialogue();
				},
				ex = function () {
					var position = {
						left: body.find('.export-button')[0].offsetLeft,
						top: body.find('.top-menu').height() + 2
					};
					
					var exportHtml = $('<div></div>');
					dialogue(exportHtml, position);
					
					exportHtml.exportdialogue();
				},
				bug = function () {
					window.open("https://code.google.com/p/moodle-senior-design/issues/entry");
				},
				wiki = function () {
					window.open("/moodleqb/pmwiki-2.2.60/pmwiki.php");
				};
				
			self.addButton('Open', open, 'GFX/Open.png', 'open-button');
			self.addButton('Save', save, 'GFX/Save.png', 'save-button');
			self.addButton('Export', ex, 'GFX/Export.png', 'export-button');
			self.addButton('Report Bug', bug, 'GFX/Bug.png', 'report-button');
			self.addButton('Help', wiki, 'GFX/Wiki.png', 'wiki-button');
			
		},
		
		addButton: function (label, action, img, cls) {
			var self = this,
				e = self.element,
				data = {img: img, label: label},
				button = template("top-menu-button-tmpl", data).appendTo(e);
			
			button.on('click', function () {
				doc.trigger('closedialogue');
			});
			button.on('click', action);
			
			button.addClass(cls);
		}
		
	});	
	
	var dialogue = function (html, position) {
		var dialogue = $('<div></div>').appendTo(body);
		dialogue.dialogue({
			html: html,
			position: position
		});
	};
	
	$.widget("MQM.dialogue", {
	
		options: {
			html: null,
			position: null
		},

		_create: function () {
			var self = this,
				e = self.element;
				o = self.options;
				
			e.html(o.html);
			e.addClass('dialogue');
			e.css({
				top: o.position.top-3,
				left: o.position.left
			});
			
			doc.on('closedialogue', function () {
				e.fadeOut(130 , function () {
					e.remove();
				});
			});
		}
		
	});
	
	$.widget("MQM.exportdialogue", {
		_create: function () {
			var self = this,
				e = self.element;
				
			e.html(template("export-dialogue-tmpl"));
			
			var file = e.find('.file-name'),
				select = e.find('.format-select');
			
			self.okayButton = e.find('.okay').on('click', function () {
				doc.trigger('closedialogue');
				format = select.find(':selected').data('value');
				filename = file.val();
				
				var bank = "";
				if(format === 'xml')
				{
					bank += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<quiz>\n";
				}
				$.each(seeds, function (key, seed) {
					if (format === 'txt') {
						bank += seed.genGift();
					} else if (format === 'xml') {
						bank += seed.genXML();
					}
				});
				if(format === 'xml')
				{
					bank += "\n</quiz>\n";
				}
				
				saveFile(bank, filename + '.' + format);
			});
			
			self.cancelButton = e.find('.cancel').on('click', function () {
				doc.trigger('closedialogue');
			});
		}
	});
	
	$.widget("MQM.savedialogue", {
		_create: function () {
			var self = this,
				e = self.element;
				
			e.html(template("save-dialogue-tmpl"));
			
			var filename = e.find('.file-name');
			console.log(seeds);
			self.okayButton = e.find('.okay').on('click', function () {
				doc.trigger('closedialogue');
				var file = "";
				$.each(seeds, function (key, seed) {
					file += seed.genQSD();
				});
				saveFile(file, filename.val() + '.qsd');
			});
			
			self.cancelButton = e.find('.cancel').on('click', function () {
				doc.trigger('closedialogue');
			});
		}
	});
	
	$(topMenu).menuButtons();
	$(window).resize();
});
